import { useState, useRef, useEffect } from 'react';
// import { history } from 'umi';
import { Button, Space, Modal, message, Tag } from 'antd';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { PowerTable } from '@/components/CommonTable';
import AddUserFormModal from '../components/AddPageModal';
import ChooseChannelModal from '../components/ChooseChannelModal';
import RenameModal from '../components/RenameModal';
import DeleteModal from '../components/DeleteModal';
import CommonPageContainer from '@/components/CommonPageContainer';
import { PageLoading } from '@ant-design/pro-layout';
import { useParams } from 'umi';

import {
  querypageManagementList,
  setUpdateName,
  deleteManagement,
  copyManagement,
  queryTemplateList,
  saveOrUpdate,
  updateStatus,
  previewData,
} from '@/services/management.service';
import type { ProColumns } from '@ant-design/pro-table';
import './index.less';

const HomePage = () => {
  const [visible, setVisible] = useState(false);
  const [delVisible, setDelVisible] = useState(false);
  const [renameVisible, setRenameVisible] = useState(false);
  const [channelVisible, setChannelVisible] = useState(false);
  const [selected, setSelected] = useState<any>();
  const [templateList, setTemplateList] = useState([]);
  const [rowId, setRowId] = useState(-1);
  const [rowName, setRowName] = useState('');
  const [rowStatus, setRowStatus] = useState('');
  const [rowChannel, setRowChannel] = useState('');
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const cRef = useRef<any>();
  const [modal, contextHolder] = Modal.useModal();
  const [open, setOpen] = useState(false);
  const [qrCode, setQrCode] = useState('');
  const [pageLoading, setPageLoading] = useState(false);

  const routeParams = useParams<Record<'type', string>>();

  const init = async () => {
    const params: any = {
      type: routeParams.type || 1,
    };
    try {
      const { code, message: msg, data } = await queryTemplateList(params);
      if (code === 0) {
        setTemplateList(data);
      } else {
        message.error(msg);
      }
    } catch (error) {}
  };

  useEffect(() => {
    init();
  }, [routeParams]);

  // 新建页面
  const handleOperationBtn = () => {
    setConfirmLoading(false);
    setVisible(true);
  };

  // 新增/编辑/点击确定触发
  const handleAddSubmit = async (val: any) => {
    // history.push(
    //   `/decoration/editor/create?name=${val.name}&channel=${val.channel}&id=${val.template}&type=1`,
    // );
    window.open(
      `${window.origin}${window.location.pathname}#/decoration/editor/create?name=${
        val.name
      }&channel=${val.channel}&id=${val.template}&type=${routeParams.type || 1}`,
      '_blank',
    );
    setVisible(false);
  };

  // 删除
  const handleDelete = (info: any) => {
    setRowId(info.id);
    setRowName(info.name);
    setDelVisible(true);
  };

  // 删除弹窗确认
  const handleDelSubmit = async () => {
    const params: any = {
      id: rowId,
    };
    setConfirmLoading(true);
    try {
      const { code, message: msg } = await deleteManagement(params);
      if (code === 0) {
        message.success('操作成功');
        setDelVisible(false);
        setConfirmLoading(false);
        cRef?.current?.reload();
      } else {
        message.error(msg);
      }
    } catch (error) {}
  };

  // 复制弹窗确认
  const handleCopySubmit = async (id: number) => {
    const params: any = {
      id,
    };
    try {
      const { code, message: msg } = await copyManagement(params);
      if (code === 0) {
        message.success('操作成功');
        cRef?.current?.reload();
      } else {
        message.error(msg);
      }
    } catch (error) {}
  };

  // 复制
  const handleCopy = (info: any) => {
    setRowId(info.id);
    // setCopyVisible(true);
    modal.confirm({
      title: '是否需要复制该页面',
      icon: <ExclamationCircleOutlined />,
      content: '复制后，将会生成一个草稿状态的副本页面',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        handleCopySubmit(info.id);
      },
    });
  };

  // 重命名
  const handleRename = (info: any) => {
    setRowId(info.id);
    setRenameVisible(true);
  };

  // 选择渠道 编辑
  const handleChanne = (info: any) => {
    if (info.copy === 1) {
      setRowId(info.id);
      setRowName(info.name);
      setRowStatus(info.status);
      setRowChannel(info.channelCode);
      setChannelVisible(true);
    } else {
      // history.push(`/decoration/editor/edit?id=${info.id}`);
      window.open(
        `${window.origin}${window.location.pathname}#/decoration/editor/edit?id=${info.id}`,
        '_blank',
      );
    }
  };

  // 重命名确认
  const handleRenameSubmit = async (e: any) => {
    const params: any = {
      name: e.name,
      id: rowId,
    };
    setConfirmLoading(true);
    try {
      const { code, message: msg } = await setUpdateName(params);
      if (code === 0) {
        message.success('操作成功');
        setRenameVisible(false);
        setConfirmLoading(false);
        cRef?.current?.reload();
      } else {
        message.error(msg);
      }
      setRenameVisible(false);
      setConfirmLoading(false);
    } catch (error) {}
  };

  // 切换页面配置渠道弹窗确认
  const handleChannelSubmit = async (e: any) => {
    setConfirmLoading(true);
    const params: any = {
      name: e.name,
      id: rowId,
      channelCode: e.channel,
      copy: 0,
      status: rowStatus,
    };
    try {
      const { code, message: msg } = await saveOrUpdate(params);
      if (code === 0) {
        message.success('操作成功');
        setChannelVisible(false);
        setConfirmLoading(false);
        cRef?.current?.reload();
        // history.push(`/decoration/editor/edit?id=${rowId}`);
        window.open(
          `${window.origin}${window.location.pathname}#/decoration/editor/edit?id=${rowId}&channel=${rowChannel}`,
          '_blank',
        );
      } else {
        message.error(msg);
        setChannelVisible(false);
        setConfirmLoading(false);
      }
    } catch (error) {}
  };

  // 确认使用
  const handleUseSubmit = async (info: any) => {
    const params: any = {
      id: info.id,
      status: 3,
    };
    try {
      const { code, message: msg } = await updateStatus(params);
      if (code === 0) {
        message.success('操作成功');
        cRef?.current?.reload();
      } else {
        message.error(msg);
      }
    } catch (error) {}
  };

  // 使用
  const handleUseModal = (info: any) => {
    modal.confirm({
      title: '是否需要使用该页面',
      icon: <ExclamationCircleOutlined />,
      content: '使用后，对应渠道的路径将会立刻使用该页面样式，原页面将会被替换下线',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        handleUseSubmit(info);
      },
    });
  };

  // 预览
  const handlePreview = async (record: any) => {
    setPageLoading(true);
    const { code, message: msg, data } = await previewData({ id: record.id });
    if (code === 0) {
      setQrCode(data);
    } else {
      message.error(msg);
    }
  };

  useEffect(() => {
    if (qrCode) {
      setOpen(true);
      setPageLoading(false);
    }
  }, [qrCode]);

  const columns: ProColumns<any, string>[] = [
    {
      title: '页面名称',
      width: 120,
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '状态',
      width: 80,
      dataIndex: 'status',
      align: 'center',
      valueEnum: {
        0: { text: '草稿', status: '0' },
        2: { text: '已发布', status: '2' },
        3: { text: '使用中', status: '3' },
        4: { text: '定时发布', status: '4' },
      },
      render: (_text, record) => (
        <>
          {record.status === 0 && <Tag color="default">草稿</Tag>}
          {record.status === 2 && <Tag color="geekblue">已发布</Tag>}
          {record.status === 3 && <Tag color="cyan">使用中</Tag>}
          {record.status === 4 && <Tag color="blue">定时发布</Tag>}
        </>
      ),
    },
    {
      title: '投放渠道',
      width: 120,
      dataIndex: 'channelCode',
      align: 'center',
      valueEnum: {
        '0002': { text: '微信小程序', status: '0002' },
        '0003': { text: 'H5', status: '0003' },
      },
      render: (_text, record) => (
        <>
          {record.channelCode === '0002' && <span>微信小程序</span>}
          {record.channelCode === '0003' && <span>H5</span>}
        </>
      ),
    },
    {
      title: '更新人',
      width: 120,
      dataIndex: 'updateName',
      search: false,
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      search: false,
      align: 'center',
      valueType: 'dateTime',
      width: 170,
    },
    {
      title: '操作',
      align: 'center',
      search: false,
      width: 400,
      fixed: 'right',
      render: (_text, record) => (
        <Space>
          {/* <Popover content={() => preview(record)} title="请使用微信扫一扫预览" trigger="click">

          </Popover> */}

          {record.status !== 0 && (
            <Button className="table-btn" type="link" onClick={() => handlePreview(record)}>
              预览
            </Button>
          )}

          <Button
            className="table-btn"
            type="link"
            onClick={() => {
              handleChanne(record);
            }}
          >
            开始配置
          </Button>
          {record.status !== 3 && (
            <Button
              className="table-btn"
              type="link"
              onClick={() => {
                handleDelete(record);
              }}
            >
              删除
            </Button>
          )}
          <Button
            className="table-btn"
            type="link"
            onClick={() => {
              handleRename(record);
            }}
          >
            重命名
          </Button>
          <Button
            className="table-btn"
            type="link"
            onClick={() => {
              handleCopy(record);
            }}
          >
            复制页面
          </Button>
          {record.status === 2 && (
            <Button
              type="link"
              className="table-btn"
              onClick={() => {
                handleUseModal(record);
              }}
            >
              使用
            </Button>
          )}
          {/* <Button type="link" className="table-btn" onClick={() => {}}>
            定时发布
          </Button> */}
        </Space>
      ),
    },
  ];

  return (
    <CommonPageContainer>
      {pageLoading && (
        <div className="loadingBox">
          <PageLoading />
        </div>
      )}
      <PowerTable
        dataKey="data"
        headerTitle="页面地址列表"
        columns={columns}
        tableAlertOptionRender={false}
        tableAlertRender={false}
        fetchAction={querypageManagementList}
        cRef={cRef}
        params={{
          type: routeParams.type || 1,
        }}
        rowKey="id"
        toolBarRender={() => [
          <Button key="add" type="primary" icon={<PlusOutlined />} onClick={handleOperationBtn}>
            新建页面
          </Button>,
        ]}
      />

      {/* 预览 */}
      <Modal
        title="请使用微信扫一扫预览"
        centered
        open={open}
        onOk={() => setOpen(false)}
        onCancel={() => setOpen(false)}
        width={300}
      >
        <div>
          <span className="qrtext">有效期大约为30分钟</span>
          <img className="qrcode" src={qrCode} />
        </div>
      </Modal>

      {/* 新增/编辑弹框 */}
      <AddUserFormModal
        visible={visible}
        confirmLoading={confirmLoading}
        onSubmit={handleAddSubmit}
        selected={selected}
        onCancel={() => {
          setVisible(false);
        }}
        templateList={templateList}
        onSelect={setSelected}
        operInfo={{}}
        operTitle={'add'}
      />
      {/* 重命名弹框 */}
      <RenameModal
        visible={renameVisible}
        confirmLoading={confirmLoading}
        onSubmit={handleRenameSubmit}
        onCancel={() => {
          setRenameVisible(false);
        }}
      />
      {/* 删除弹窗 */}
      <DeleteModal
        open={delVisible}
        modalText={rowName}
        confirmLoading={confirmLoading}
        onSubmit={handleDelSubmit}
        onCancel={() => {
          setDelVisible(false);
        }}
      />
      {/* 开启配置，在复制信息之后只会触发一次 */}
      <ChooseChannelModal
        visible={channelVisible}
        confirmLoading={confirmLoading}
        name={rowName}
        onSubmit={handleChannelSubmit}
        onCancel={() => {
          setChannelVisible(false);
        }}
      />
      {contextHolder}
    </CommonPageContainer>
  );
};

export default HomePage;
